<template>
	<view class="confirm-order">
		<g-navbar title="确认订单" backgroundColor="#365fff" fontColor="#ffffff" />
		<view class="main">
			<addressModule :address="currentAddress" />
			<goodsDetail :totalPrice="totalPrice" :count="orderParams?orderParams.count:0" :detail="detail" />
			<orderOptions :totalPrice="totalPrice" :currentPayOption="currentPayOption"
				:currentDeliverOption="currentDeliverOption" @updateCurrentDeliverOption="updateCurrentDeliverOption"
				@updateCurrentPayOption="updateCurrentPayOption" />
		</view>
		<payBar :totalPrice="totalPrice" :count="orderParams?orderParams.count:0" @order="order" v-if="detail" />
	</view>
</template>

<script lang="ts" setup>
	import payBar from './components/pay-bar/payBar.vue';
	import addressModule from './components/address-module/addressModule.vue';
	import goodsDetail from './components/goods-detail/goodsDetail';
	import orderOptions from './components/order-options/orderOptions.vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { ORDER_TYPE } from '@/enum/goods';
	import { Ref, ref, computed } from "vue";
	import REST_URL from '@/http/http.restUrl';
	import { IAddress } from '@/types/address';
	import { useStore } from 'vuex';
	import { DEFAULT_TYPE } from '@/enum/address';
	import type { IPayOption, IDeliverOption } from '@/global';
	import global from '@/global';
	import { PAY_STATUS, PAY_WAY_TYPE } from '@/enum/pay';
	import { DELIVER_TYPE } from '@/enum/deliver';
	import { ROUTE_TYPE } from '@/enum/router';
	import { GET_STORE_USERINFO } from '@/store/gettersType';

	interface IOrderParams {
		id : number,
		count : number,
		type : ORDER_TYPE,
	}

	const orderParams : Ref<IOrderParams | null> = ref(null);

	const detail : Ref<IGoods | null> = ref(null);

	const addressList : Ref<IAddress[]> = ref([]);

	const currentAddress : Ref<IAddress | null> = ref(null);

	const currentPayOption : Ref<IPayOption> = ref(global.payOptionList[PAY_WAY_TYPE.BALANCE]);

	const currentDeliverOption : Ref<IDeliverOption> = ref(global.deliverOptionList[DELIVER_TYPE.EXPRESS]);


	const updateCurrentPayOption = (e : IPayOption) => {
		currentPayOption.value = e;
	}

	const updateCurrentDeliverOption = (e : IDeliverOption) => {
		currentDeliverOption.value = e;
	}


	const store = useStore();

	onLoad(async (e) => {
		await uni.loginManger.$interceptor;
		orderParams.value = (e as IOrderParams);
		await getGoodsDetailById();
		await getDeliveryAddress();
	})


	const totalPrice = computed(() => {
		if (!orderParams.value || !detail.value) {
			return 0
		}
		return orderParams.value.count * Number(detail.value?.retail_price);
	})

	uni.$off('selectAddress');
	uni.$on('selectAddress', async (id : number) => {
		const selectedAddress : IAddress | undefined = addressList.value.find(item => item.id == id);
		if (selectedAddress) {
			currentAddress.value = selectedAddress;
		} else {
			await getDeliveryAddress();
			currentAddress.value = (addressList.value.find(item => item.id == id) as IAddress);
		}
	})


	const getGoodsDetailById = async () : Promise<void> => {
		const data : IGoods = (await uni.http.POST(REST_URL.getGoodsDetailById, {
			product_id: orderParams.value!.id,
		})).data
		detail.value = data;
	}

	const getDeliveryAddress = async () => {
		const result : IAddress[] = (await uni.http.POST(REST_URL.getDeliveryAddress, {
			customer_id: store.getters[GET_STORE_USERINFO].id,
		})).data;
		console.log(result)
		addressList.value = result ? result : [];
		if (addressList.value.length) {
			currentAddress.value = (addressList.value.find((item : IAddress) => item.default === DEFAULT_TYPE.SET) as IAddress);
		}
	}

	interface IOrderOptions {
		customer_id : number,
		product_id : number,
		product_number : number,
		pay_type : PAY_WAY_TYPE,
		address_id : number,
		distribution_type : DELIVER_TYPE,
	}

	interface IConfimOrderResult {
		order_num : string;
		pay_time : string;
		submit_time : string;
		pay_type : PAY_WAY_TYPE;
		pay_amount_total : string;
		pay_status : PAY_STATUS;
	}

	const order = async () => {


		if (!currentAddress.value) {
			return uni.prompt.$showToast('请添加收货地址')
		}
		const result = await placeOrder();
		switch (currentPayOption.value.type) {
			case PAY_WAY_TYPE.WECHAT:
				console.log('微信支付')
				jumpCheckstand(result.order_num);
				break;
			case PAY_WAY_TYPE.ALIPAY:
				break;
			case PAY_WAY_TYPE.BALANCE:
				jumpDetail(result.order_num);
				break;
		}
	}

	const jumpDetail = (orderNum : string) => {
		uni.router.route({
			url: '/pages_mall/order_detail/orderDetail',
			type: ROUTE_TYPE.REDIRECTTO,
			params: {
				orderNum
			}
		})
	}

	const jumpCheckstand = (orderNum : string) => {
		uni.router.route({
			url: '/pages_mall/checkstand/checkstand',
			type: ROUTE_TYPE.REDIRECTTO,
			params: {
				orderNum
			}
		})
	}

	const placeOrder = async () : Promise<IConfimOrderResult> => {
		const restUrl : string = orderParams.value!.type == ORDER_TYPE.USER ? REST_URL.userOrder : REST_URL.agentOrder;
		const options : IOrderOptions = {
			customer_id: store.getters[GET_STORE_USERINFO].id,
			product_id: detail.value!.id,
			product_number: orderParams.value!.count,
			pay_type: currentPayOption.value.type,
			address_id: currentAddress.value!.id,
			distribution_type: currentDeliverOption.value.type,
		}
		const result : IConfimOrderResult = (await uni.http.POST(restUrl, options)).data;
		console.log('下单成功，跳转到支付')
		return result
	}
</script>

<style scoped lang="scss">
	@import "./confirmOrder.scss";
</style>